package com.example.project2;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    //声明控件对象
    EditText first, second;
    Button concatenate, clear_all;
    TextView result;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //关联控件对象
        first = findViewById(R.id.text_first);
        second = findViewById(R.id.text_second);
        concatenate = findViewById(R.id.btn1);
        clear_all = findViewById(R.id.btn2);
        result = findViewById(R.id.textView);

        //ViewModel对象的创建
        final TextViewModel textViewModel = new ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(getApplication())).get(TextViewModel.class);

        //设置Concatenate按钮的监听事件，调用TextViewModel的union函数将输入的两个字符串合并在一起
        concatenate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                textViewModel.union(first.getText().toString(), second.getText().toString());
            }
        });

        //增加LiveData机制，调用onChanged函数将结果显示在UI界面上
        textViewModel.getStr().observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                //设置结果文本为可见
                result.setVisibility(View.VISIBLE);
                result.setText(s);
            }
        });

        //设置Clear All按钮的监听事件，清空文本框的所有值
        clear_all.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                first.setText("");
                second.setText("");
                result.setText("");
                //设置结果文本为不可见
                result.setVisibility(View.INVISIBLE);
            }
        });

    }
}